package com.school.fuyuan.business;

import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.school.fuyuan.business.mapper.InfoManageMapper;
import com.school.fuyuan.business.mapper.UserMapper;
import com.school.fuyuan.business.model.po.InfoManage;
import com.school.fuyuan.business.model.po.User;
import com.school.fuyuan.common.util.InfoManageUtil;
import com.school.fuyuan.common.util.JSONArrayListUtil;
import com.school.fuyuan.common.util.ParameterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/14 23:05
 * @description
 */
@Controller
public class FileController {
    @Autowired
    ConfigurableApplicationContext context;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final UserMapper userMapper;
    private final InfoManageMapper infoManageMapper;
    private final InfoManageUtil infoManageUtil;

    public FileController(UserMapper userMapper, InfoManageMapper infoManageMapper, InfoManageUtil infoManageUtil) {
        this.userMapper = userMapper;
        this.infoManageMapper = infoManageMapper;
        this.infoManageUtil = infoManageUtil;
    }

    @GetMapping(value = "/file")
    public String singleUpload() {
        return "file";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        log.info("[文件大小] - [{}]", file.getSize());
        ExcelReader reader = null;
        Map<String, Object> resultMap = new HashMap<>();
        try {
            reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> readAll = reader.readAll();
            log.info("Excel upload:{}", readAll);
            StringBuilder msg = new StringBuilder();
            List<InfoManage> infoManages = new ArrayList<>();
            if (!ParameterUtils.isEmpty(readAll)) {
                for (int i = 0; i < readAll.size() - 1; i++) {
                    Map<String, Object> map = readAll.get(i);
                    String callDate = String.valueOf(map.get("callDate"));
                    String callTime = String.valueOf(map.get("callTime"));
                    String studentName = String.valueOf(map.get("studentName"));
                    String infoState = String.valueOf(map.get("infoState"));
                    String infoSource = String.valueOf(map.get("infoSource"));
                    String consultationContent = String.valueOf(map.get("consultationContent"));
//                    String createUserMobile = String.valueOf(map.get("createUserId"));
//                    String followPersonMobile = String.valueOf(map.get("followPersonId"));
                    String order = String.valueOf(map.get("order"));
                    if (ParameterUtils.hasAnyEmpty(callDate,callTime, studentName, infoState, consultationContent,order)) {
                        msg.append(order + "必填信息存在空\r\n");
                        break;
                    }
//                    User createUser = userMapper.getUserByMobile(createUserMobile);
//                    if (ParameterUtils.isEmpty(createUser)) {
//                        msg.append("序号:" + order + "的" + createUserMobile + "用户不存在\r\n");
//                        continue;
//                    }
//
//                    User followPerson = userMapper.getUserByMobile(followPersonMobile);
//                    if (ParameterUtils.isEmpty(followPerson)) {
//                        msg.append("序号:" + order + "的" + followPersonMobile + "用户不存在\r\n");
//                        continue;
//                    }

                    String appointment = String.valueOf(map.get("appointment"));

                    String considerAdmissionTime = String.valueOf(map.get("considerAdmissionTime"));
//                    if (StringUtils.hasText(considerAdmissionTime)) {
//                        considerAdmissionTime = considerAdmissionTime.split(" ")[0];
//                    }

                    String contactNumMain = String.valueOf(map.get("contactNumMain"));
                    String parentNameMain = String.valueOf(map.get("parentNameMain"));
                    String contactNumOther = String.valueOf(map.get("contactNumOther"));
                    String parentNameOther = String.valueOf(map.get("parentNameOther"));
                    String currentSchool = String.valueOf(map.get("currentSchool"));
                    String currentGrade = String.valueOf(map.get("currentGrade"));
                    String homeAddress = String.valueOf(map.get("homeAddress"));
                    String remark = String.valueOf(map.get("remark"));
                    String mathScore = String.valueOf(map.get("mathScore"));
                    String mathGrade = String.valueOf(map.get("mathGrade"));
                    String englishScore = String.valueOf(map.get("englishScore"));
                    String englishGrade = String.valueOf(map.get("englishGrade"));
                    String phyChemScore = String.valueOf(map.get("phyChemScore"));
                    String phyChemGrade = String.valueOf(map.get("phyChemGrade"));

                    InfoManage infoManage = new InfoManage();
//                    infoManage.setFollowPersonName(followPerson.getUserName());
//                    infoManage.setFollowPersonId(followPerson.getUserId());
//                    infoManage.setCreateUserId(createUser.getUserId());
                    infoManage.setCallTime(callTime);
                    infoManage.setInfoState(infoState);
                    infoManage.setInfoSource(infoSource);
                    infoManage.setStudentName(studentName);
                    infoManage.setConsultationContent(consultationContent);

                    if (StringUtils.hasText(contactNumMain) && !"null".equalsIgnoreCase(contactNumMain.trim())) {
                        infoManage.setContactNumMain(contactNumMain);
                    }
                    if (StringUtils.hasText(parentNameMain) && !"null".equalsIgnoreCase(parentNameMain.trim())) {
                        infoManage.setParentNameMain(parentNameMain);
                    }
                    if (StringUtils.hasText(contactNumOther) && !"null".equalsIgnoreCase(contactNumOther.trim())) {
                        infoManage.setContactNumOther(contactNumOther);
                    }
                    if (StringUtils.hasText(parentNameOther) && !"null".equalsIgnoreCase(parentNameOther.trim())) {
                        infoManage.setParentNameOther(parentNameOther);
                    }

                    if (StringUtils.hasText(currentSchool) && !"null".equalsIgnoreCase(currentSchool.trim())) {
                        infoManage.setCurrentSchool(currentSchool);
                    }
                    if (StringUtils.hasText(currentGrade) && !"null".equalsIgnoreCase(currentGrade.trim())) {
                        infoManage.setCurrentGrade(currentGrade);
                    }
                    if (StringUtils.hasText(homeAddress) && !"null".equalsIgnoreCase(homeAddress.trim())) {
                        infoManage.setHomeAddress(homeAddress);
                    }
                    if (StringUtils.hasText(remark) && !"null".equalsIgnoreCase(remark.trim())) {
                        infoManage.setRemark(remark);
                    }
                    if (StringUtils.hasText(mathScore) && !"null".equalsIgnoreCase(mathScore.trim())) {
                        infoManage.setMathScore(mathScore);
                    }
                    if (StringUtils.hasText(mathGrade) && !"null".equalsIgnoreCase(mathGrade.trim())) {
                        infoManage.setMathGrade(mathGrade);
                    }
                    if (StringUtils.hasText(englishScore) && !"null".equalsIgnoreCase(englishScore.trim())) {
                        infoManage.setEnglishScore(englishScore);
                    }
                    if (StringUtils.hasText(englishGrade) && !"null".equalsIgnoreCase(englishGrade.trim())) {
                        infoManage.setEnglishGrade(englishGrade);
                    }
                    if (StringUtils.hasText(phyChemScore) && !"null".equalsIgnoreCase(phyChemScore.trim())) {
                        infoManage.setPhyChemScore(phyChemScore);
                    }
                    if (StringUtils.hasText(phyChemGrade) && !"null".equalsIgnoreCase(phyChemGrade.trim())) {
                        infoManage.setPhyChemGrade(phyChemGrade);
                    }
                    if (StringUtils.hasText(appointment) && !"null".equalsIgnoreCase(appointment.trim())) {
                        infoManage.setAppointment(appointment);
                    }
                    if (StringUtils.hasText(considerAdmissionTime) && !"null".equalsIgnoreCase(considerAdmissionTime.trim())) {
                        infoManage.setConsiderAdmissionTime(considerAdmissionTime);
                }
                    infoManageMapper.insertInfoManage(infoManage);
                    int id = infoManage.getId();
                    try {
                        if (!ParameterUtils.isEmpty(appointment)) {
                            Date appointmentDate = DateUtil.parse(appointment, "yyyy-MM-dd");
                            //前一天的10点
                            Date yesterdayTen = infoManageUtil.getApptDate(appointment, -1, 10, 0, 0);

                            // 前天的16点
                            Date yesterdaySixteen = infoManageUtil.getApptDate(appointment, -1, 16, 0, 0);
                            infoManageUtil.sendApptMq(yesterdayTen, id, appointmentDate);
                            infoManageUtil.sendApptMq(yesterdaySixteen, id, appointmentDate);
                        }
                    } catch (DateException e) {
                        msg.append("序号:" + order + "的" + appointment + "格式不合法\r\n");
                    }
                }
            }
//            if (!ParameterUtils.isEmpty(infoManageList)) {
//                infoManageMapper.batchAddInfoManage(infoManageList);
//            }
//            file.transferTo(new File(context.getEnvironment().getProperty("info.excel.entering.position") + System.currentTimeMillis() + file.getOriginalFilename()));
            if (ParameterUtils.isEmpty(msg)) {
                msg.replace(0, 4, "success");
            }
            resultMap.put("msg", msg.toString());
            resultMap.put("code", "0");
        } catch (IOException e) {
            resultMap.put("msg", "fail");
            resultMap.put("code", "-1");
        }
        return resultMap;
    }

    @PostMapping("/upload2")
    @ResponseBody
    public List<Map<String, String>> upload2(@RequestParam("file") MultipartFile[] files) throws IOException {
        if (files == null || files.length == 0) {
            return null;
        }
        List<Map<String, String>> results = new ArrayList<>();
        for (MultipartFile file : files) {
            // TODO Spring Mvc 提供的写入方式
            file.transferTo(new File("E:\\" + file.getOriginalFilename()));
            Map<String, String> map = new HashMap<>(16);
            map.put("contentType", file.getContentType());
            map.put("fileName", file.getOriginalFilename());
            map.put("fileSize", file.getSize() + "");
            results.add(map);
        }
        return results;
    }

    @PostMapping("/upload3")
    @ResponseBody
    public void upload2(String base64) throws IOException {
        // TODO BASE64 方式的 格式和名字需要自己控制（如 png 图片编码后前缀就会是 data:image/png;base64,）
        final File tempFile = new File("E:\\test.jpg");
        // TODO 防止有的传了 data:image/png;base64, 有的没传的情况
        String[] d = base64.split("base64,");
        final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
        FileCopyUtils.copy(bytes, tempFile);

    }

    @RequestMapping("/downloadFile")
    @ResponseBody
    private String downloadFile(HttpServletResponse response) {
        String downloadFilePath = context.getEnvironment().getProperty("info.model.position");
//        String downloadFilePath = "E:\\code\\info-manage\\src\\main\\resources\\model.xlsx";//被下载的文件在服务器中的路径,
        String fileName = "model.xlsx";//被下载文件的名称
        File file = new File(downloadFilePath);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "下载失败";
    }


    /**
     * @param response
     * @return
     */
    @GetMapping("/exportInfosFile/{userId}")
    @ResponseBody
    private String exportInfosFile(HttpServletResponse response, @PathVariable String userId) {
//        String downloadFilePath = context.getEnvironment().getProperty("info.model.position");
//        String downloadFilePath = "E:\\code\\info-manage\\src\\main\\resources\\model.xlsx";//被下载的文件在服务器中的路径,
        String fileName = "infos.xlsx";//被下载文件的名称
        Map<String, String> headMap = new LinkedHashMap<>();
        headMap.put("callTime", "来电时间");
        headMap.put("studentName", "学生姓名");
        headMap.put("infoState", "信息状态");
        headMap.put("appointment", "预约时间");
        headMap.put("considerAdmissionTime", "考虑入学时间");
        headMap.put("consultationContent", "咨询内容");
        headMap.put("contactNumMain", "联系电话1");
        headMap.put("parentNameMain", "家长姓名1");
        headMap.put("contactNumOther", "联系电话2");
        headMap.put("parentNameOther", "家长姓名2");
        headMap.put("currentSchool", "在读学校");
        headMap.put("currentGrade", "在读年级");
        headMap.put("homeAddress", "家庭住址");
        headMap.put("infoSource", "信息来源");
        headMap.put("remark", "特别备注");
        headMap.put("mathScore", "数学分数");
        headMap.put("mathGrade", "数学等级");
        headMap.put("englishScore", "英语分数");
        headMap.put("englishGrade", "英语等级");
        headMap.put("phyChemScore", "物化分数");
        headMap.put("phyChemGrade", "物化等级");
        List<InfoManage> infoManageList = infoManageMapper.getInfoManageList(userId, 0, 0);
        JSONArray jsonArray = JSONArrayListUtil.getJSONArrayByList(infoManageList);
        com.school.fuyuan.common.util.ExcelUtil.downloadExcelFile(fileName, headMap, jsonArray, response);
        return "下载成功";
    }
}